<template>
  <div class="GISMap">
    <!-- <div class="btns">
      <el-button type="primary" @click="setDraw">开始绘画</el-button>
      <el-button type="primary" @click="removeDraw">结束绘画</el-button>
    </div> -->

    <div class="plane-detail" v-if="details">
      <div class="head">
        <h2>详情</h2>
        <p class="close" @click="details = null">×</p>
      </div>
      <div class="wrapper">
        <div v-for="(item, index) in details">
          <div class="d-t">
            <span>{{ index }}：</span>
            <span>{{ item || '-' }}</span>
          </div>
        </div>        
      </div>
    </div>
    <div ref='mapCon' id="mapCon"> </div>

    <!-- <div class="info-box">
      <div class="alert-table">
        <h2>当前警戒区域</h2>
        <el-table
          height="calc(100vh - 120px)"
          :data="alertTableData">
          <el-table-column label="点集">
            <template #default="scope">
              <div>
                <div v-for="(item, index) in scope.row.points" :key="index">
                  {{ Math.floor(item[0] * 100) / 100 + ', ' +  Math.floor(item[1] * 100) / 100 }}
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="开始时间" prop="start"></el-table-column>
          <el-table-column label="结束时间" prop="end"></el-table-column>
        </el-table>
      </div>
    </div> -->

    <!-- <div class="plane-box"></div> -->
  </div>
</template>

<script lang="ts" setup>
import 'ol/ol.css'
import Map from 'ol/Map.js'
import View from 'ol/View'
import TileLayer from 'ol/layer/Tile'
import XYZ from "ol/source/XYZ"
import { fromLonLat, toLonLat } from 'ol/proj'  // OpenLayers的投影转换函数，用于经纬度坐标和投影坐标之间的转换

import Plane from '@/config/third-plugins/mapTool/plane'
import DrawGeometry from '@/config/third-plugins/mapTool/draw'

import {getTopLeft, getTopRight, getBottomLeft, getBottomRight} from 'ol/extent'

import Feature from 'ol/Feature'  // OpenLayers的要素类，表示地图上的一个对象或实体
import Polygon from "ol/geom/Polygon"  // OpenLayers的多边形几何类，用于表示面状的地理数据
import { Vector as VectorLayer } from 'ol/layer'  // OpenLayers的矢量图层类，用于显示矢量数据
import { Vector as VectorSource } from 'ol/source'  // OpenLayers的矢量数据源类，用于管理和提供矢量数据
import { Style, Stroke, Fill } from "ol/style"  // OpenLayers的样式类，用于定义图层的样式，包括圆形样式、基本样式、边框、填充和图标
// import { ElMessage } from 'element-plus'

import {defaults as defaultControls} from 'ol/control';

const MapDom = ref()
const mapCon = ref(null)

const originData = ref()

const plane = ref()

const drawer = ref()
// const areaPoints = ref()
// const ageing = ref()

const details = ref()

const alertTableData = ref()

const InitDraw = () => {
  // const tk = 'f8a3b4d864a022d6505d479995108369'
  const tdtVectorLayer = new TileLayer({
    source: new XYZ({
      url: 'http://192.168.5.63:8080' + '/{z}/{x}/{y}.png'
    })
  })

  // 渲染一个地图 需要一个视图Map、一个或多个层view和一个目标容器dom
  // 创建视图 map
  MapDom.value = new Map({
    // 创建图层
    view: new View({
      // center: [0, 0],
      center: fromLonLat([108.924652, 34.208527]), // 地图中心点定位北京
      zoom: 1,
      minZoom: 1,
      constrainResolution: true // 因为存在非整数的缩放级别，所以设置该参数为true来让每次缩放结束后自动缩放到距离最近的一个整数级别，这个必须要设置，当缩放在非整数级别时地图会糊
    }),
    layers: [
      tdtVectorLayer
    ],
    target: mapCon.value || '',
    controls: defaultControls({
      zoom: false,
      rotate: false,
      attribution: false
    })
  });

  plane.value = new Plane()

  plane.value.addFirstTimePlane('1', [116.4, 39.9])
  // plane.value.addPlaneLine([[116.4, 39.9], [125.315833, 43.799167]])
  plane.value.addPlaneLine([[116.4, 39.9], [111.76, 40.83]])

  plane.value.setSouce()
  plane.value.setLayer()

  MapDom.value.addLayer(plane.value.planeLayer)
  MapDom.value.addLayer(plane.value.planeLineLayer)

  plane.value.updateToward(0, [111.76, 40.83])

  drawer.value = new DrawGeometry(MapDom.value)
}

const initPlane = () => {
  const date = new Date()
  // $ajax.post('states_query', {
  //   // icao24: '',
  //   time_min: Number(parseInt((date.getTime() - 1000) / 1000 + '')),
  //   time_max: Number(parseInt(date.getTime() / 1000 + ''))
  // }).then((res:any) => {
  //   const { code, data } = res
  //   if (code === 200) {
  //     if (data && data.states && JSON.stringify(data.states) !== '{}') {
  //       // 首次请求数据
  //       if (!originData.value) {
  //         const planeData:any = []
  //         for (const key in data.states) {
  //           planeData.push({
  //             id: key,
  //             position: [data.states[key].lon, data.states[key].lat]
  //           })
  //         }
  //         planeData.forEach((i:any) => {
  //           plane.value.addFirstTimePlane(i.id, i.position)
  //         })
  //         plane.value.setSouce()
  //         plane.value.setLayer()
  //         MapDom.value.addLayer(plane.value.planeLayer)
  //       } else {
  //         // 删除消失的飞机
  //         for (const key1 in originData.value) {
  //           // 删除消失的飞机
  //           if (!data.states[key1]) {
  //             // plane.value.delPlane(key1)
  //           }
  //         }

  //         for (const key2 in data.states) {
  //           if (originData.value[key2]) {
  //             // 更新已存在的飞机位置及朝向
  //             plane.value.updatePlane(key2 + '', [data.states[key2].lon, data.states[key2].lat])
  //           } else {
  //             // 添加新的飞机
  //             plane.value.addPlane(key2 + '', [data.states[key2].lon, data.states[key2].lat])
  //           }
  //         }
  //       }

  //       originData.value = data.states
  //     } else {
  //       // console.log('clear')
  //     }
  //   }
  // })
}

const getAlertData = () => {
  const date = new Date()
  $ajax.get('danger_area_time_point', {
    time_point: Number(parseInt(date.getTime() / 1000 + ''))
  }).then(res => {
    alertTableData.value = res.data.map((i:any) => {
      let start:any = i.start_time * 1000
      let end:any = i.end_time * 1000
      start = new Date(start)
      start = start.toLocaleDateString() + ' ' + start.toLocaleTimeString()
      end = new Date(end)
      end = end.toLocaleDateString() + ' ' + end.toLocaleTimeString()
      return {
        end,
        start,
        points: i.points,
        type: i.typecode
      }
    })

    let drawData = alertTableData.value.map((j:any) => {
      return j.points
    })

    drawData = drawData.map((k:any) => {
      const d = k.map((p:any) => {
        return fromLonLat(p)
      })

      return [d]
    })

    // drawer.value.drawAllArea(drawData)
  })
}

const getViewRange = () => {
  MapDom.value.on('moveend', (event:any) => {
    //获取可视化区域得范围
    let coods = event.map.getView().calculateExtent( event.map.getSize())

    let postcooders:any = [getTopLeft(coods), getTopRight(coods), getBottomRight(coods) ,getBottomLeft(coods)] // 可视区域为一个多边形，需是闭合的
    postcooders = postcooders.map((i:any) => {
      return toLonLat(i)
    })

    // console.log(postcooders)
  })
}

const setDraw = () => {
  drawer.value.drawMethod()

  // 监控画图结束时，获取图上的点
  drawer.value.draw.on('drawend', (event:any) => {
    const geometry = event.feature.getGeometry()
    const coordinates = geometry.getCoordinates()
    // 最后一个点不要
    let temp = coordinates[0]
    temp = temp.slice(0, temp.length - 1)
    temp = temp.map((i:any) => {
      return toLonLat(i)
    })

    const date = new Date()
    const start = date.getTime() - 1000 * 60 * 60 * 12
    const end = date.getTime() + 1000 * 60 * 60 * 12
    $ajax.post('danger_area', {
      start_time: Number(parseInt(start / 1000 + '')),
      end_time: Number(parseInt(end / 1000 + '')),
      points: temp
    }).then(res => {
      if (res.code === 200) {
        ElMessage({
          type: 'success',
          message: '添加成功'
        })
        getAlertData()
      }
    })
  })
}
const removeDraw = () => {
  drawer.value.removeDrawMethod()
}

// 测试可视化范围是否正确
const faceMethod = (coordinates:any) => {
  // 创建多边形的几何对象
  let polygon = new Polygon(coordinates)

  // 创建特征（Feature）
  let polygonFeature = new Feature({
    geometry: polygon
  })

  // 设置多边形的样式（Style）
  polygonFeature.setStyle(
    new Style({
      stroke: new Stroke({
        color: 'red', // 多边形边界线的颜色
        width: 2 // 多边形边界线的宽度
      }),
      fill: new Fill({
        color: 'rgba(255, 0, 0, 0.5)' // 多边形填充颜色，这里设置为半透明红色
      })
    })
  )

  // 创建和添加特征到源（Source）
  let source = new VectorSource()
  source.addFeature(polygonFeature)

  // 创建图层并设置源（Layer）
  let layer = new VectorLayer()
  layer.setSource(source)

  // 将图层添加到地图上
  MapDom.value.addLayer(layer)
}

onMounted(() => {
  InitDraw()
})

</script>
<style scoped lang="scss">
  .GISMap {
    position: relative;
    .btns {
      position: absolute;
      left: 45px;
      top: 15px;
      z-index: 10;
    }
    height: calc(100vh - 60px);
    #mapCon {
      width: calc(100vw - 0px);
      height: 100%;
    }
    .info-box {
      width: 500px;
      height: 100%;
      padding: 15px;
      box-sizing: border-box;
      position: absolute;
      top: 0;
      right: 0;
      background-color: #e0e3ea;
      .alert-table {
        h2 {
          margin-bottom: 3px;
        }
      }
    }
    .plane-detail {
      height: calc(100vh - 90px);
      display: flex;
      flex-direction: column;
      padding: 0px 0px 0px 0px;
      box-sizing: border-box;
      position: absolute;
      left: 15px;
      top: 15px;
      z-index: 10;
      background-color: rgba(77, 84, 92, 0.5);
      width: 300px;
      .d-t {
        line-height: 21px;
        margin-bottom: 6px;
        padding: 0 20px;
        box-sizing: border-box;
        color: #000;
      }
      .head {
        display: flex;
        justify-content: space-between;
        padding: 10px 10px;
        box-sizing: border-box;
        color: #000;
        .close {
          cursor: pointer;
        }
      }
      .wrapper {
        flex: 1;
        overflow-y: auto;
      }
    }

    .plane-box {
      width: 500px;
      height: calc(100vh - 60px);
      position: absolute;
      right: 0;
      top: 0px;
      background-color: #e0e3ea;
    }
  }
</style>